import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from "axios";

axios.interceptors.request.use(config => {
  // 是否需要设置 token
  if(store.state.token){
    config.headers['Authorization'] = "Bearer "+store.state.token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
});
// 添加响应拦截器，401的错误注销并跳转到登录页面
axios.interceptors.response.use(
  response => {
    let data = response.data;
    if(data.code == 401){
      // 显示错误信息
      Vue.prototype.$message.error(data.msg);
      // 注销清除登录数据
      store.commit("logout");
      // 跳转到登录页面
      router.push({path: '/login'});
      // 不需要响应了
      return;
    }
    if(data.code == 403){
      // 显示错误信息
      Vue.prototype.$message.error(data.msg);
      // 不需要响应了
      return;
    }
    return response;
});
// 在Vue原型上绑定axios对象  
Vue.prototype.$axios = axios; 

// 引用ElementUI插件
import ElementUI from 'element-ui';
// 引用ElementUI样式
import 'element-ui/lib/theme-chalk/index.css';
// 通过Vue.use注册插件
Vue.use(ElementUI);

Vue.config.productionTip = false

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
Vue.component('treeselect', Treeselect)

import {handleTree } from "@/utils/common";
Vue.prototype.handleTree = handleTree; 

// // 直接在main.js中定义并注册v-hasPermi指令
Vue.directive('hasPermi', {
  inserted(el, binding) {
    const { value } = binding
    const all_permission = "*:*:*";
    const permissions = store.state.userInfo.permissions

    if (value) {
      let hasPermissions=false;
      permissions.forEach((item)=>{
        if(item==value || item==all_permission){
          hasPermissions=true;
          return;
        }
      })
      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el)
      }
      
    } else {
      throw new Error(`请设置操作权限标签值`)
    }
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
